package hk.edu.polyu.comp446.group5;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//used to collection stock data but no link to current system

public class StockTickerDAO {
	private static final Log log = LogFactory.getLog(StockTickerDAO.class);
	private static final StockTickerDAO stockDAO = new StockTickerDAO();
	private static HashMap<String, StockBean> stocks = new HashMap<String, StockBean>();
	private static final long TWENTY_MIN = 1200000;

	private StockTickerDAO() {
	}

	public static StockTickerDAO getInstance() {
		return stockDAO;
	}

	// StockBean will return null if unable to retrieve information  
	public StockBean getStockPrice(String symbol) {
		StockBean stock;
		long currentTime = (new Date()).getTime();

		// Check last updated and only pull stock on average every 20 minutes
		if (stocks.containsKey(symbol)) {
			stock = stocks.get(symbol);
			if (currentTime - stock.getLastUpdated() > TWENTY_MIN) {
				stock = refreshStockInfo(symbol, currentTime);
			}
		} else {
			stock = refreshStockInfo(symbol, currentTime);
		}
		return stock;
	}

	// This is synched so we only do one request at a time
	// If yahoo doesn't return stock info we will try to return it from the map in memory
	private synchronized StockBean refreshStockInfo(String symbol, long time) {
		Calendar cal = Calendar.getInstance();
		int endofyear = cal.get(Calendar.YEAR);
		//for (int i = 0; i < totalYear.length; i++){
		//for (int j = 0; j <= 11; j++){
		String stockData = "";
		try {
			URL yahoofin = new URL("http://ichart.yahoo.com/table.csv?s=" + symbol + "&a=" + "" + "&b=1&c=" + "" + "&d=9&e=31&f=" + endofyear
					+ "&g=m&ignore=.csv");
			URLConnection yc = yahoofin.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			in.skip(42); // Skip the Headline
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				String[] yahooStockInfo = inputLine.split(",");
				System.out.println("" + yahooStockInfo[0]);
				StockBean stockInfo = new StockBean();
				stockInfo.setTicker(yahooStockInfo[0].replaceAll("\"", ""));
				stockData = symbol + "," + String.valueOf(yahooStockInfo[0]) + "," + Float.valueOf(yahooStockInfo[6]) + "\n" + stockData;
				stockInfo.setPrice(Float.valueOf(yahooStockInfo[6]));
				stockInfo.setDate(String.valueOf(yahooStockInfo[0]));
				stockInfo.setChartUrlSmall("http://ichart.finance.yahoo.com/t?s=" + stockInfo.getTicker());
				stockInfo.setChartUrlLarge("http://chart.finance.yahoo.com/w?s=" + stockInfo.getTicker());
				stockInfo.setLastUpdated(time);
				stocks.put(symbol, stockInfo);
			}
			in.close();
		} catch (Exception ex) {
			log.error("Unable to get stockinfo for: " + symbol + ex);
		}
		//}
		//}

		try {
			BufferedWriter out = new BufferedWriter(new FileWriter("stockdata.txt"));
			out.write(stockData);
			out.close();
		} catch (IOException e) {
			System.out.println("Exception ");
		}
		return stocks.get(symbol);
	}
}
